package server;

import java.io.IOException;
import java.io.InputStream;

/**
 * @Author: Tao Zheng
 * @classNmae: Request
 * @packageName: server
 * @description: 把请求信息封装为Request对象（根据InputStream输入流封装）
 * @DATE: 2021/7/13 15:55
 */
public class Request {
    private String method;
    private String url;
    private String host;
    private InputStream inputStream;

    public String getMethod() {
        return method;
    }

    public void setMethod(String method) {
        this.method = method;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public InputStream getInputStream() {
        return inputStream;
    }

    public void setInputStream(InputStream inputStream) {
        this.inputStream = inputStream;
    }

    public String getHost() {
        return host;
    }

    public void setHost(String host) {
        this.host = host;
    }

    public Request(InputStream inputStream) throws IOException {
        this.inputStream = inputStream;

        // 从输入流中获取请求信息
        int count = 0;
        while (count == 0){
            count = inputStream.available();
        }
        byte[] bytes = new byte[count];
        inputStream.read(bytes);

        String inputStr = new String(bytes);
        String firstLineStr = inputStr.split("\\n")[0];  // GET / HTTP/1.1
        String[] strings = firstLineStr.split(" ");
        this.method = strings[0];
        this.url = strings[1];

        // 获取第二行请求头信息
        String secondLineStr = inputStr.split("\\n")[1];  // Host: localhost:8080
        this.host = secondLineStr.split(":")[1].trim();

        System.out.println("========>>>>method：" + method);
        System.out.println("========>>>>url：" + url);

        System.out.println("========>>>>请求信息：" + new String(bytes));
    }
}
